from sqlalchemy import Column, String, Text, Integer, DateTime
from sqlalchemy.orm import relationship
from ..database import Base
from utils.id_util import generate_id
from .user_role_do import UserRoleModel
from .role_permission_do import RolePermissionModel
from .user_do import UserModel
import datetime

class RoleModel(Base):
    __tablename__ = "roles"

    id = Column(String, primary_key=True, default=generate_id, index=True)
    name = Column(String, unique=True, index=True, nullable=False)
    # access = Column(String, unique=True, index=True, nullable=False)
    # description = Column(Text, nullable=True)
    status = Column(Integer, default=1, nullable=False)  # 0: 禁用, 1: 启用
    remark = Column(Text, nullable=True)  # 备注信息
    createTime = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)

    user_roles = relationship("UserRoleModel", backref="role", cascade="all, delete-orphan")
    users = relationship("UserModel", secondary="user_roles", viewonly=True)

    role_permissions = relationship("RolePermissionModel", backref="role", cascade="all, delete-orphan")
    permissions = relationship("PermissionModel", secondary="role_permissions", viewonly=True)

    def to_dict(self):
        """
        转换为符合前端SystemRoleApi.SystemRole接口的字典格式
        """
        return {
            "id": self.id,
            "name": self.name,
            # "access": self.access,
            # "description": self.description,
            "status": self.status,
            "createTime": self.createTime.strftime("%Y-%m-%d %H:%M:%S") if self.createTime else None,
            "remark": self.remark
        }
